<template>
    <el-scrollbar height="400px">
      <div class="header">
        <el-tooltip content="复制" placement="top">
          <el-icon class="copy-btn" @click="handleCopy">
            <CopyDocument />
          </el-icon>
        </el-tooltip>
      </div>
      <div class="pre-text">
        <el-input
          id="sql-textarea-content"
          type="textarea"
          :rows="15"
          v-model="textData"
          readonly
        ></el-input>
      </div>
    </el-scrollbar>
  </template>
  
  <script>
  import { CopyDocument } from '@element-plus/icons-vue';
 
  
  export default {
    name: 'TextAreaCopy',
    components: {
      CopyDocument
    },
    props: {
      text: {
        type: String,
        default: ''
      }
    },
    data() {
      return {
        textData: this.text,
        clipboard: null // 用于存储ClipboardJS实例
      };
    },
    watch: {
      text(newValue) {
        this.textData = newValue;
      }
    },
    methods: {
      handleCopy() {
        // 如果支持现代浏览器的剪贴板API，则直接使用它
        if (navigator && navigator.clipboard && navigator.clipboard.writeText) {
          this.copyUsingModernAPI();
        } else {
          // 否则使用ClipboardJS
          this.clipboard.trigger('click');
        }
      },
      async copyUsingModernAPI() {
        try {
          await navigator.clipboard.writeText(this.textData);
          this.$message.success('复制成功');
        } catch (err) {
          this.$message.error('复制失败，请手动复制。');
        }
      }
    }
  };
  </script>
  
  <style scoped>
  .pre-text {
    white-space: pre;
    border: 1px solid #ccc;
    background-color: #f9f9f9;
    margin-top: 8px;
  }
  
  .header {
    position: absolute;
    top: 0;
    right: 0;
    z-index: 1;
    margin: 10px;
  }
  </style>